package com.study.utils;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.script.ScriptUtil;
import com.alibaba.fastjson2.JSON;
import com.study.dto.Student;
import com.study.dto.SubDTO;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.jupiter.api.Test;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.net.HttpCookie;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhuzi
 * 2024/3/27 00:01
 */
public class HutoolHttp {
    public static String cookieV() {
        try {
            File file = ResourceUtils.getFile("classpath:js/aes.min.js");
            String scrript = FileUtil.readString(file.getPath(), StandardCharsets.UTF_8);
            Object v1 = ScriptUtil.invoke(scrript, "v");
            return v1.toString();
        } catch (FileNotFoundException e) {
        }
        return null;
    }

    @Test
    public void gets() {
        HttpResponse response = HttpRequest.get("https://t.10jqka.com.cn/lgt/article_query/open/api/article/v1/detail?pid=345819858").execute();

        System.out.println(response.body());
    }

    @Test
    public void get() {
        String url = "https://t.10jqka.com.cn/lgt/article_query/open/api/article/v1/detail?pid=345819858";
        HttpResponse response = HttpRequest.get(url).executeAsync();

        //System.out.println(response.body());
    }

    @Test
    public void strDemoCenter() {
        String ste = StrUtil.center("\uD83D\uDCE3 算力工程", 20, "*");
        System.out.println(ste);
    }

    @Test
    public void getRespCookie() {
        String url = "https://t.10jqka.com.cn/lgt/user_page/?userid=651751555#/";
        HttpResponse response = HttpRequest.get(url).execute();


        List<HttpCookie> cookies = response.getCookies();
        cookies.forEach(c -> {
            System.out.println(c);
        });
        String body = response.body();
        System.out.println(body);
    }

    @Test
    public void postThs() {
        String url = "https://t.10jqka.com.cn/user_center/open/api/content/v2/get_by_uid";
        Map<String, String> headerMap = MapUtil.<String, String>builder()
                //.put("Cookie", "v=A4iUqQteeqgHPZYsjXKbNYz_X_efMe0mzpXAv0I51IP2HSYj6kG8yx6lkK6R")
                .put("Host", "t.10jqka.com.cn")
                //.put("Upgrade-Insecure-Requests", "1")
                //.put("Sec-Fetch-Dest", "document")
                //.put("Sec-Fetch-Mode", "navigate")
                //.put("Sec-Fetch-Site", "none")
                //.put("Sec-Fetch-User", "?1")
                //.put("Origin", null)
                //.put("Content-Length", "21")
                .build();
        HttpResponse response = HttpRequest.post(url).headerMap(headerMap, true).contentType(ContentType.JSON.getValue()).body("{\"user_id\":651751555}").execute();

        System.out.println(response.getCookieStr());
        System.out.println(response.body());

    }

    @Test
    public void cls() {
        String url = "https://api1.cls.cn/share/article/1627420s";
        HttpResponse response = HttpRequest.get(url).execute();
        System.out.println(response.body());
        System.out.println(response.getStatus());

    }

    @Test
    public void clsArticle() {
        String url = "https://api3.cls.cn/share/article/1627420";
        url = "https://www.cls.cn/detail/1627420";
        HttpResponse response = HttpRequest.get(url).execute();

        String body = response.body();

        Document docRoot = Jsoup.parse(body);

        Elements content = docRoot.select(".m-b-40.detail-content p");

        for (Element element : content) {
            System.out.println(element);
            System.out.println(StrUtil.repeat("-", 50));
        }

    }

    @Test
    public void json() {
        for (int i = 0; i < 1; i++) {
            Student student = new Student().setId((long) i).setName("学号" + i).setBirth(LocalDate.now().minusDays(i)).setAge(i + 18);
            SubDTO subDTO = new SubDTO<>().setType("CEB30" + i).setPubDateTime(LocalDateTime.now()).setData(student);

            //虽然PUBLISH命令不会因为没有订阅者而失败，但是你可以检查返回值是否等于0，这表示当前没有任何订阅者接收到消息，但发布动作本身是成功的。

            String jsonString = JSON.toJSONString(subDTO);
            System.out.println(jsonString);
            SubDTO subDTO1 = JSON.parseObject(jsonString, SubDTO.class);
            System.out.println(subDTO1);
        }
    }

    @Test
    public void getZtfx() {

        String urlZtfx = "https://app.jiuyangongshe.com/jystock-app/api/v1/action/diagram-url";

        Map<String, String> header = new HashMap<>();


        header.put("Host", "app.jiuyangongshe.com");
        header.put("Connection", "keep-alive");

        header.put("sec-ch-ua-platform", "macOS");
        header.put("timestamp", System.currentTimeMillis() + "");
        header.put("sec-ch-ua", "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"");
        header.put("sec-ch-ua-mobile", "?0");
        header.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36");
        //header.put("Accept", "application/json, text/plain, */*");
        //header.put("Accept-Language", "zh-CN,zh;q=0.9");
        //header.put("Content-Type", "application/json");
        //header.put("Referer", "https://www.jiuyangongshe.com/");
        //header.put("Sec-Fetch-Dest", "empty");
        //header.put("Sec-Fetch-Mode", "cors");
        //header.put("Sec-Fetch-Site", "same-site");
        //header.put("Origin", "https://www.jiuyangongshe.com");
        header.put("platform", "3");
        header.put("token", "1e7ece0a768c47453d30f16d12fe9724");

        HttpResponse execute = HttpRequest.post(urlZtfx)
                .headerMap(header, true)
                .cookie("SESSION=YWEzMzdkZjYtZWNlNC00NDIxLTg0OWItOWI1OGRiNTNhNjI4")
                .body("{\"date\":\"2024-11-26\"}")
                .timeout(8 * 1000).execute();
        String body = execute.body();
        System.out.println(body);


    }

    @Test
    public void getSdgd() {
        String url = "https://datacenter.eastmoney.com/securities/api/data/get?type=RPT_F10_EH_HOLDERS&sty=SECUCODE%2CEND_DATE%2CHOLDER_NAME%2CHOLDER_CODE%2CHOLDER_CODE_OLD%2CHOLD_NUM%2CHOLD_NUM_RATIO%2CHOLD_RATIO_QOQ%2CHOLDER_RANK%2CIS_HOLDORG%2CHOLDER_NEW%2CNEW_CHANGE_RATIO&filter=%28SECUCODE%3D%22300729.SZ%22%29%28END_DATE%3D%272024-03-31%27%29&client=APP&source=SECURITIES&pageNumber=1&pageSize=200&sr=1";

        String body = HttpRequest.get(url).execute().body();
        System.out.println(body);
    }

    @Test
    public void getList() {
        List<String> strings = FileUtil.readLines("/Users/zhuzi/Downloads/工作簿2.csv", StandardCharsets.UTF_8);

        List<CsvValue> collect = strings.stream().map(ia -> {
            String[] split = ia.split(",");
            CsvValue csvValue = new CsvValue();
            LocalDate localDate = LocalDateTimeUtil.parseDate(split[0], "yyyy/M/d");
            csvValue.setDate(localDate);
            csvValue.setVal(NumberUtil.toBigDecimal(split[1]));
            return csvValue;
        }).sorted(Comparator.comparing(CsvValue::getDate)).collect(Collectors.toList());

        String collect1 = collect.stream().map(ia -> "'" + ia.getDate() + "'").collect(Collectors.joining(","));
        System.out.println(collect1);

        String collect2 = collect.stream().map(ia -> ia.getVal().toString()).collect(Collectors.joining(","));
        System.out.println(collect2);


    }

    @Data
    @Accessors(chain = true)
    @ToString
    static class CsvValue {
        private LocalDate date;
        private BigDecimal val;
    }
}
